# coding:utf-8
class Admin::AdminsController < AdminController

  respond_to :html, :json
  set_tab :permissions
  set_tab :permissions, :sub_nav
  before_filter :get_groups, only: [:new, :edit, ]
  before_filter :setup, only: [:index,:zone]

  def index
    @users = Admin.desc
  end

  def show

  end

  def new
    @user = Admin.new
  end

  def create
    group_ids = params[:admin].delete(:group_ids)
    @user = Admin.new(params[:admin])
    if @user.save
      #unless current_admin.god?
        current_admin.zone_permissions.each do |zp|
          ZonePermission.create(admin_id: @user.id,
            entity: zp.entity,
            entity_id: zp.entity_id)
        end
      #end

      UserGroupship.where(user_id: @user.id).each do |t|
        unless group_ids.include?(t.group_id.to_s)
          t.destroy
        end
      end

      Group.where(id: group_ids).each do |t|
        UserGroupship.where(group_id: t.id, user_id: @user.id).first_or_create
      end
    else
      render :action => :new 
    end 
  end

  def edit
    @user = Admin.find(params[:id])
  end

  def edit_password
    @user = Admin.find(params[:id])
  end

  def update
    @user = Admin.find(params[:id])
    group_ids = params[:admin].delete(:group_ids)
    if @user.update_attributes(params[:admin])
      UserGroupship.where(user_id: @user.id).each do |t|
        unless group_ids.include?(t.group_id.to_s)
          t.destroy
        end
      end

      Group.where(id: group_ids).each do |t|
        UserGroupship.where(group_id: t.id, user_id: @user.id).first_or_create
      end
    else
      render :action => :edit
    end
  end

  def update_password
    @user = Admin.find(params[:id])
    if @user.update_attributes(params[:admin])

    else
      render :action => :edit_password 
    end
  end

  def zone
    @user = Admin.find(params[:id])
    @ways << @user.email
  end

  def update_zone
    params[:user_permissions].each do |key,value|
      if key =~ /([a-z0-9A-Z_]+)_(\d*)/
        entity,entity_id = $1,$2
        permission = ZonePermission.where(admin_id: params[:user_permissions][:user_id],
          entity: entity.classify,
          entity_id: entity_id.to_i).first
        case value
        when "0"
          permission.destroy if permission
        when "1"
          permission = ZonePermission.create(admin_id: params[:user_permissions][:user_id],
            entity: entity.classify,
            entity_id: entity_id.to_i) unless permission
        end
      end
    end
    redirect_to zone_admin_admin_url(user_id: params[:user_permissions][:user_id])
  end

  private

  def setup
    @ways = ["权限管理","用户管理"]
    @left_panel = "layouts/admin_left_panel"
  end

  def get_groups
    if current_admin.god?
      @groups = Group.where(category: ["Department","Role"]).all
    else
      @groups = Group.where(category: ["Department"]).where(["name != ?","Administration"]).all
    end
  end
  
end